# strategy_design.py - 策略设计
import pandas as pd
import matplotlib.pyplot as plt
import numpy as  np

class CouponStrategy:
    def __init__(self, user_features, cluster_descriptions, prediction_model=None):
        self.user_features = user_features
        self.cluster_descriptions = cluster_descriptions
        self.prediction_model = prediction_model

    def design_cluster_based_strategy(self):
        """设计基于客户分群的策略"""
        print("\n" + "=" * 50)
        print("1. 基于客户价值分群的差异化策略")
        print("=" * 50)

        strategies = {}

        for cluster_id, cluster_info in self.cluster_descriptions.items():
            description = cluster_info['description']
            cluster_size = cluster_info['size']
            metrics = cluster_info['metrics']

            # 根据分群特征设计策略
            if "高价值" in description:
                strategy = {
                    'name': 'VIP专属策略',
                    'coupon_type': 'VIP专属券(8-9折)',
                    'frequency': '月度发放',
                    'amount': '中等面额',
                    'goal': '客户维护和忠诚度提升',
                    'channels': ['APP推送', '专属客服', '会员专享页面']
                }
            elif "重要发展" in description:
                strategy = {
                    'name': '频次提升策略',
                    'coupon_type': '满减券/折扣券(7-8折)',
                    'frequency': '双周发放',
                    'amount': '中高面额',
                    'goal': '提升购买频次和客户价值',
                    'channels': ['短信提醒', 'APP消息', '邮件营销']
                }
            elif "潜力" in description:
                strategy = {
                    'name': '习惯培养策略',
                    'coupon_type': '通用优惠券(8.5-9.5折)',
                    'frequency': '每周发放',
                    'amount': '中小面额',
                    'goal': '培养消费习惯和品牌认知',
                    'channels': ['APP推送', '社交媒体', '精准广告']
                }
            else:
                strategy = {
                    'name': '激活策略',
                    'coupon_type': '新人券/大额券(6-7折)',
                    'frequency': '活动期间发放',
                    'amount': '大面额',
                    'goal': '刺激消费和客户激活',
                    'channels': ['广点通广告', '新人专享', '活动页面']
                }

            strategies[cluster_id] = strategy

            # 输出策略详情
            print(f"\n🔹 分群 {cluster_id}: {description}")
            print(f"   📊 客户规模: {cluster_size}人 ({cluster_size / len(self.user_features):.1%})")
            print(f"   🎯 策略名称: {strategy['name']}")
            print(f"   💰 优惠券类型: {strategy['coupon_type']}")
            print(f"   📅 发放频率: {strategy['frequency']}")
            print(f"   🎯 策略目标: {strategy['goal']}")
            print(f"   📱 投放渠道: {', '.join(strategy['channels'])}")

        return strategies

    def design_prediction_based_strategy(self):
        """设计基于预测模型的策略"""
        if self.prediction_model is None:
            print("未提供预测模型，跳过预测策略")
            return None

        print("\n" + "=" * 50)
        print("2. 基于预测模型的精准投放策略")
        print("=" * 50)

        strategies = {
            'high_propensity': {
                'threshold': 0.8,
                'strategy': '高频次精准投放',
                'action': '优先发放，培养忠诚度',
                'monitoring': '重点跟踪转化率'
            },
            'medium_high_propensity': {
                'threshold': (0.6, 0.8),
                'strategy': '定期维护投放',
                'action': '定期发放，维持活跃',
                'monitoring': '监测行为变化'
            },
            'medium_low_propensity': {
                'threshold': (0.4, 0.6),
                'strategy': '测试性投放',
                'action': '选择性发放，观察效果',
                'monitoring': 'A/B测试效果'
            },
            'low_propensity': {
                'threshold': (0, 0.4),
                'strategy': '谨慎投放',
                'action': '减少发放，避免浪费',
                'monitoring': '长期观察'
            }
        }

        for level, strategy_info in strategies.items():
            print(f"\n📈 {strategy_info['strategy']}:")
            print(f"   概率区间: {strategy_info['threshold']}")
            print(f"   投放动作: {strategy_info['action']}")
            print(f"   监控重点: {strategy_info['monitoring']}")

        return strategies

    def design_temporal_strategy(self):
        """设计时间策略"""
        print("\n" + "=" * 50)
        print("3. 时间策略")
        print("=" * 50)

        temporal_strategies = {
            'holidays': {
                'periods': ['春节', '双11', '618', '国庆节'],
                'strategy': '全量发放节日专属优惠券',
                'discount': '大力度折扣(5-7折)',
                'goal': '刺激节日消费'
            },
            'member_days': {
                'periods': ['每月8号会员日', '季度会员周'],
                'strategy': '会员专属优惠券',
                'discount': '会员专属折扣(7-8折)',
                'goal': '提升会员忠诚度'
            },
            'off_season': {
                'periods': ['1-2月', '6月下旬', '9月'],
                'strategy': '增加发放频率和力度',
                'discount': '促销折扣(6-8折)',
                'goal': '平衡季节性波动'
            },
            'new_products': {
                'periods': ['新品上市期'],
                'strategy': '新品专属优惠券',
                'discount': '新品体验价(8-9折)',
                'goal': '促进新品推广'
            }
        }

        for scenario, strategy in temporal_strategies.items():
            print(f"\n🕒 {strategy['strategy']}:")
            print(f"   适用时期: {', '.join(strategy['periods'])}")
            print(f"   优惠力度: {strategy['discount']}")
            print(f"   策略目标: {strategy['goal']}")

        return temporal_strategies

    def design_regional_strategy(self):
        """设计地域策略"""
        print("\n" + "=" * 50)
        print("4. 地域策略")
        print("=" * 50)

        # 分析地域消费特征
        regional_stats = self.user_features.groupby('省份').agg({
            '总消费额': 'mean',
            '购买频次': 'mean',
            '客单价': 'mean',
            '用户ID': 'count'
        }).round(2)

        regional_stats.columns = ['平均消费额', '平均购买频次', '平均客单价', '用户数']
        regional_stats = regional_stats.sort_values('平均消费额', ascending=False)

        # 高消费地区
        top_regions = regional_stats.head(3)
        print("📍 高消费地区策略:")
        for region, stats in top_regions.iterrows():
            print(f"   {region}: 平均消费¥{stats['平均消费额']}, {stats['用户数']}用户")
            print(f"     策略: 维持优质服务，发放会员权益类优惠券")
            print(f"     目标: 客户维护和交叉销售")

        # 低消费地区
        bottom_regions = regional_stats.tail(3)
        print(f"\n📍 低消费地区策略:")
        for region, stats in bottom_regions.iterrows():
            print(f"   {region}: 平均消费¥{stats['平均消费额']}, {stats['用户数']}用户")
            print(f"     策略: 加大优惠力度，发放引流型大额优惠券")
            print(f"     目标: 市场渗透和客户激活")

        return {
            'high_consumption_regions': top_regions,
            'low_consumption_regions': bottom_regions
        }

    def design_personalization_strategy(self):
        """设计个性化策略"""
        print("\n" + "=" * 50)
        print("5. 个性化推荐策略")
        print("=" * 50)

        personalization_strategies = [
            {
                'type': '基于购买历史',
                'approach': '推荐相关品类优惠券',
                'example': '购买过母婴用品的用户推送母婴品类券',
                'technology': '协同过滤算法'
            },
            {
                'type': '基于浏览行为',
                'approach': '实时推送浏览商品优惠券',
                'example': '浏览未购买的商品推送专属优惠券',
                'technology': '实时推荐引擎'
            },
            {
                'type': '基于消费金额',
                'approach': '动态调整优惠券面额',
                'example': '高消费用户推送更高面额优惠券',
                'technology': '动态定价算法'
            },
            {
                'type': '基于购物车',
                'approach': '发放购物车商品专属优惠券',
                'example': '购物车商品滞留推送降价提醒',
                'technology': '购物车分析系统'
            }
        ]

        for strategy in personalization_strategies:
            print(f"\n🎯 {strategy['type']}:")
            print(f"   方法: {strategy['approach']}")
            print(f"   示例: {strategy['example']}")
            print(f"   技术: {strategy['technology']}")

        return personalization_strategies

    def design_evaluation_framework(self):
        """设计效果评估框架"""
        print("\n" + "=" * 50)
        print("6. 效果评估与优化机制")
        print("=" * 50)

        evaluation_framework = {
            'A/B Testing': {
                'purpose': '对比不同策略效果',
                'metrics': ['转化率', 'ROI', '客单价提升'],
                'frequency': '持续进行'
            },
            'ROI Monitoring': {
                'purpose': '跟踪优惠券投入产出比',
                'metrics': ['单券成本', '带来的增量收入', '长期价值'],
                'frequency': '每周评估'
            },
            'User Feedback': {
                'purpose': '收集用户满意度',
                'metrics': ['优惠券使用率', '用户评分', '投诉率'],
                'frequency': '每月收集'
            },
            'Strategy Review': {
                'purpose': '定期复盘策略效果',
                'metrics': ['各策略KPI达成', '市场变化', '竞争对比'],
                'frequency': '季度复盘'
            }
        }

        for area, details in evaluation_framework.items():
            print(f"\n📋 {area}:")
            print(f"   目的: {details['purpose']}")
            print(f"   关键指标: {', '.join(details['metrics'])}")
            print(f"   评估频率: {details['frequency']}")

        return evaluation_framework

    def create_strategy_dashboard(self):
        """创建策略总览仪表板"""
        print("\n" + "=" * 60)
        print("优惠券投放策略总览")
        print("=" * 60)

        # 执行所有策略设计
        cluster_strategies = self.design_cluster_based_strategy()
        prediction_strategies = self.design_prediction_based_strategy()
        temporal_strategies = self.design_temporal_strategy()
        regional_strategies = self.design_regional_strategy()
        personalization_strategies = self.design_personalization_strategy()
        evaluation_framework = self.design_evaluation_framework()

        # 汇总策略
        summary = {
            'cluster_strategies': cluster_strategies,
            'prediction_strategies': prediction_strategies,
            'temporal_strategies': temporal_strategies,
            'regional_strategies': regional_strategies,
            'personalization_strategies': personalization_strategies,
            'evaluation_framework': evaluation_framework
        }

        # 绘制策略分布图
        self._plot_strategy_distribution(cluster_strategies)

        return summary

    def _plot_strategy_distribution(self, cluster_strategies):
        """绘制策略分布图"""
        if not cluster_strategies:
            return

        # 准备数据
        strategy_data = []
        for cluster_id, strategy in cluster_strategies.items():
            cluster_size = self.cluster_descriptions[cluster_id]['size']
            strategy_data.append({
                'strategy': strategy['name'],
                'cluster': f'分群{cluster_id}',
                'size': cluster_size,
                'percentage': cluster_size / len(self.user_features)
            })

        strategy_df = pd.DataFrame(strategy_data)

        # 绘制图表
        plt.figure(figsize=(12, 8))

        # 策略分布饼图
        plt.subplot(2, 2, 1)
        plt.pie(strategy_df['size'], labels=strategy_df['strategy'], autopct='%1.1f%%')
        plt.title('各策略覆盖用户分布')

        # 策略效果预期柱状图
        plt.subplot(2, 2, 2)
        expected_effect = {
            'VIP专属策略': 0.8,
            '频次提升策略': 0.6,
            '习惯培养策略': 0.4,
            '激活策略': 0.3
        }

        effects = [expected_effect.get(s, 0.5) for s in strategy_df['strategy']]
        plt.bar(strategy_df['strategy'], effects, color=['gold', 'lightcoral', 'lightblue', 'lightgreen'])
        plt.title('各策略预期效果指数')
        plt.ylabel('效果指数')
        plt.xticks(rotation=45)

        # 资源分配建议
        plt.subplot(2, 2, 3)
        resource_allocation = strategy_df['percentage'] * np.array(effects)
        resource_allocation = resource_allocation / resource_allocation.sum()
        plt.pie(resource_allocation, labels=strategy_df['strategy'], autopct='%1.1f%%')
        plt.title('建议资源分配比例')

        plt.tight_layout()
        plt.show()